﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using crmbl.Azure.WorkProcessor.Library;

namespace crmbl.Azure.WorkProcessor
{
    public class WorkProcessor : IDisposable
    {
        private WorkProcessorData _data;

        public WorkProcessor(String configConnectionString)
        {
            // Generate work config 
            WorkProcessorConfig config = new WorkProcessorConfig(); // TODO: Build the configuration

            // Create the data connection
            _data = new WorkProcessorData(config);
        }

        public void Start()
        {

        }

        private void StartScheduler()
        {
            // Start Schedulder

            // Read todo list, save to queue
            _data.SaveWorkScheduleToQueue(_data.GetNextWorkToSchedule());
        }

        private void StartRunner()
        {
            // Read next from the queue
            while (_data.GetNextWorkFromQueue().HasValue)
            {
                // Process

                // TODO : Start a new task, need governance around it
            }
        }

        private void LaunchWork(WorkDefinition w)
        {
            // http://dranaxum.wordpress.com/2008/02/25/dynamic-load-net-dll-files-creating-a-plug-in-system-c/

            //Get the information

            // Load the DLL, calls the method
            //LoadDllMethod(
        }

        private string LoadDllMethod(String titleClass, String titleVoid, String path, object[] parameters)
        {
            Assembly a = Assembly.LoadFile(path);

            Type t = a.GetType();
            
            if (t != null)
            {
                MethodInfo m = t.GetMethod(titleVoid);

                if (m != null)
                {
                    if (parameters.Length >= 1)
                    {
                        object[] myParameters = new object[1];
                        myParameters[0] = parameters;

                        return (string)m.Invoke(null,myParameters);
                    } else {
                        return (string)m.Invoke(null,null);
                    } 
                }
                throw new Exception("Method/Class {CLASS_NAME} was not found in file {FILE_NAME}.");
            }

            // TODO: Check this shit
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            try
            {
                _data.Dispose();
            }
            catch (Exception ex) { }
        }
    }
}
